package com.aliyun.heiyu.powermaster.server;

import com.aliyun.heiyu.common.util.CleanPathUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.powermaster.server.util.Configuration;
import com.google.common.base.Strings;
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeerMain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class ToolZookeeper {

    private static Logger logger = LoggerFactory.getLogger(ToolZookeeper.class);

    private static Properties zoo_properties = PropertiesUtil.getProperties("zoo.properties");

    private static String ip = Configuration.IP;

    /**
     * 启动集群机器中的zookeeper
     *
     * @param myid 指定的myid，为空时，根据IP判断myid
     * @throws IOException     IOException
     * @throws ConfigException ConfigException
     */
    public static Boolean startClusterZookeeper(String myid) {
        try {
            logger.info("=============开始启动zk服务端=============");
            if (!Strings.isNullOrEmpty(myid) && myid.matches("\\d{1}")) { // 使用指定的myid
                FileUtils.writeStringToFile(new File(CleanPathUtil.cleanString(zoo_properties.get("dataDir").toString() + "/myid")), myid, "utf-8");
            } else { // 根据ip找出myid
                for (String key : zoo_properties.stringPropertyNames()) {
                    if (key.matches("server\\.\\d{1}")) {
                        myid = key.replace("server.", "");
                        if (zoo_properties.get(key).toString().split(":")[0].equals(ip)) {
                            logger.info("===============获取到myid为" + myid + "=================");
                            FileUtils.writeStringToFile(new File(CleanPathUtil.cleanString(zoo_properties.get("dataDir").toString() + "/myid")), myid, "utf-8");
                            break;
                        }

                    }
                }
            }
            QuorumPeerConfig quorumConfig = new QuorumPeerConfig();
            quorumConfig.parseProperties(zoo_properties);
            QuorumPeerMain peer = new QuorumPeerMain();
            peer.runFromConfig(quorumConfig); // To start the replicated server
            logger.info("=============启动zk服务端完成=============");
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("============Zookeeper启动失败=============");
            return true;
        }
    }
}
